import time
import wsgiref.handlers

from google.appengine.ext import webapp
from google.appengine.api import urlfetch
from google.appengine.api import mail

class MainPage(webapp.RequestHandler):
  def get(self):
    self.response.out.write('Are Your Site is uptime now?')

class UptimeCheck(webapp.RequestHandler):
  def get(self):
    url = 'http://uhuntu.appspot.com/'
    try:
      result = urlfetch.fetch(url)
      if result.status_code == 200:
        #self.response.out.write(result.content)
        self.response.out.write('Site Online Now:%s'%time.ctime())
      else:
        SendNoticeMail(result.status_code)
        self.response.out.write('Site Offline Now:%s'%time.ctime())
    except urlfetch.DownloadError, e:
        SendNoticeMail(e)
        self.response.out.write('Site Blocked Now:%s'%time.ctime())

def SendNoticeMail(status):
  message = mail.EmailMessage(sender='uhuntu@gmail.com',
                              subject='Site Offline Notice')
  message.to = 'uhuntu@gmail.com'
  message.body = """
  Hello Hunt:

  Your site uhuntu.appspot.com is missing now. Please check it.
  The status code is %s ,%s.

  --
  hUNt0
  """ % (status,time.ctime())
  message.send()
      
application = webapp.WSGIApplication([
  ('/', MainPage),
  ('/tasks/uptime', UptimeCheck)
], debug=True)

def main():
  wsgiref.handlers.CGIHandler().run(application)

if __name__ == '__main__':
  main()
